#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/wait.h>

# include <sys/stat.h>
# include <sys/mman.h>

#define MAXLINE 100
#define SERV_PORT 9006


int main(int argc, char *argv[])
{
	struct sockaddr_in servaddr;
	char buf[MAXLINE];
	int sockfd, n;
	struct timeval outtime;
	struct stat stat;
	struct hostent *host;
	char dt_cmd[40];
	char serverip[40];
	FILE *server_fp;

	while(1)
	{
	memset(dt_cmd, 0, 40);
	strcpy(dt_cmd, "date 20");

	memset(buf,0,MAXLINE);
	
	server_fp=fopen("/mnt/nand1-2/server_ip","r");
	memset(serverip,0,40);
	if(server_fp!=NULL)
	{	     
		fgets(serverip,40,server_fp);
		fclose(server_fp);

	}
	else
	{
		sleep(5);
		return 0;
	}
	
	if(NULL == (host=gethostbyname(serverip)))
	{
		sleep(5);
		return 0;
	}

	
	if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
		printf("time create socket error\n");
	    sleep(5);
		return 0;
	}
	
	outtime.tv_sec = 10;
	outtime.tv_usec = 0;
	setsockopt(sockfd, SOL_SOCKET,SO_RCVTIMEO, &outtime,sizeof(outtime));
	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;

	servaddr.sin_addr = *((struct in_addr *)host->h_addr);
	//inet_pton(AF_INET, "192.168.2.117", &servaddr.sin_addr);
	printf("address:%s\n", inet_ntop(AF_INET,host->h_addr, buf, sizeof(buf)));

	servaddr.sin_port = htons(SERV_PORT);
	
	if( connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0 ){
		printf("connect error\n");
		close(sockfd);
		sleep(5);
	   	return 0;
	}

	memset(buf,0,MAXLINE);
	if((n = read(sockfd, buf, MAXLINE)) < 16)
	{
		close(sockfd);
		return 0;
	}
	buf[n-3] = '\0';

	buf[2]='.';
	buf[5]='.';
	buf[8]='-';
	buf[11]=':';
	buf[14]=':';

	strcat(dt_cmd,buf);
	system(dt_cmd);
	system("hwclock -w");
	close(sockfd);

	sleep(7200);
	return 0;
	}
	return 0;
}
